const api = require('../utils/api.js');
import { appId} from '../config';



/**
 * 更新用户信息
 * @param {*} detail 
 * @param {*} update 强制更新用户信息 
 */
const updateUser = async function (detail, update) {
    const app = getApp();
    if (update || !app.globalData.userInfo || !app.globalData.userInfo.unionId) {
        try {
            await api.request({
                url: 'user/mini/userInfo',
                method: 'PUT',
                data: { ...detail }
            })
        } catch (error) {

        }
    }



    try {
        v2_member(detail.userInfo)
    } catch (error) {
        error
    }

}

// 获取用户信息
const getUserInfo = async function () {
    const app = getApp();
    try {
        const res = await api.request({
            url: 'user/metadata',
        });
        app.globalData.userInfo = res.data;
        let { birthday, gender } = res.data;
        if (birthday) {
            birthday = birthday.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
        }
        Object.assign(app.globalData.userInfo, {
            birthday,
            gender: GENDERENUM[gender]
        });
    } catch (error) {

    }
    return new Promise((resolve) => {
        resolve();
    })
}


const sendFormId = function (formId) {
    if (!formId) return;
    try {
        api.request({
            url: 'user/bindFormId',
            data: { formId },
            showToast: false
        });
    } catch (error) { }
}

const claimReward = async function (params) {
    const { register } = params || {};
    const app = getApp();
    const { uuid, prizeOrderNum, prizeType } = app.globalData.prizeInfo || {};
    const { longitude = '', latitude = '' } = app.globalData.gpsInfo || {};
    wx.showLoading({ mask: true });
    const res = await api.request({
        url: `claim?longitude=${longitude}&latitude=${latitude}`,
        method: 'POST',
        data: { uuid, prizeOrderNum, register }
    });
    wx.hideLoading();
    const { prizeStatus, cashErrorCodeDes, cashErrorCode } = res.data;
    // 兑奖失败 
    if (prizeStatus == 'CLAIM_FAIL') {
        wx.showToast({
            icon: 'none',
            title: cashErrorCodeDes || cashErrorCode || '兑奖失败',
        });
        return new Promise((resolve, reject) => {
            reject();
        })
    }
    switch (prizeType) {
        case 'RED_PACKET':
            const { prizeRedPacket: { sign } } = res.data;
            return openRedPacket({ ...JSON.parse(sign), uuid, prizeOrderNum });
        default:
            return new Promise((resolve, reject) => {
                resolve(res.data);
            })
    }
}

/**
 * 拆红包
 */
const openRedPacket = (params) => {
    const { timeStamp, nonceStr, package: redPackage, signType, paySign, uuid, prizeOrderNum } = params;
    return new Promise((resolve, reject) => {
        wx.sendBizRedPacket({
            timeStamp,
            nonceStr,
            package: encodeURIComponent(redPackage),
            signType,
            paySign,
            success: res => {
                putRedClaim({ uuid, prizeOrderNum })
                resolve(res);
            },
            fail: res => {
                const { errMsg = '' } = res;
                console.log(res)
                if (!errMsg.includes('cancel')) {
                    console.log('领取失败');
                    wx.showModal({
                        icon: 'none',
                        title: JSON.stringify(res).replace('sendBizRedPacket', '红包领取失败'),
                    });
                }
                reject(res);
            }
        })
    });
}


/**
 * 更新红包
 * 
 * 
 */
const putRedClaim = function (param) {
    const { uuid, prizeOrderNum } = param;
    api.request({
        url: 'claim',
        data: { uuid, prizeOrderNum },
        method: 'put',
    });
}


const getWindowHeight = function () {
    let heigit = '100%';
    try {
        return new Promise((resolve) => {
            const res = wx.getSystemInfoSync()
            const { screenWidth, screenHeight, windowHeight } = res;
            if (screenWidth / screenHeight > 0.565) {
                heigit = `${res.screenWidth / 0.565 - screenHeight + windowHeight}px`;
                resolve(`${res.screenWidth / 0.565 - screenHeight + windowHeight}px`);
            } else {
                heigit = `${windowHeight}px`;
                resolve(`${windowHeight}px`);
            }
        });
    } catch (e) {
        heigit = '100%';
    }
    return heigit;
};

// 判断手机型号是iphone x系列，底部往上顶70rpx
const adaptiPhoneX = function () {
    const app = getApp();
    try {
        if (!app.globalData.systemInfo) {
            app.globalData.systemInfo = wx.getSystemInfoSync();
        }
        const { model = '', screenHeight, screenWidth } = app.globalData.systemInfo;

        return model.toLocaleUpperCase().includes('IPHONE') && screenHeight / screenWidth > 2 ? 70 : '';
    } catch (error) {

    }
}



/**
 * ”、“”、“”、“”、“”、“”、
 * “”、“”、“”、“”、“”、“”、“”、
 * “”、“”、“”、“”、“LBS门店-中奖页面”、“摇一摇-中奖页面”、“红包雨-中奖页面
 * 处理扫码报错弹框
 * @param {*} status 
 */
const dealScanModal = function (status) {
    let content, page, stage;
    switch (status) {
        case 'NO_PROMOTION':
            content = '暂无活动';
            break;
        case 'NO_STARTED':
            content = '活动未开始，敬请期待！';
            page = '异常状态-活动未开始';
            stage = '活动未开始';
            break;
        case 'NO_STARTED_SHAKE': case 'NO_STARTED_1231':
            content = '活动未开始，敬请期待！\r\n请关注12月31日东方卫视\r\n跨年晚会';
            page = '异常状态-活动未开始';
            stage = '活动未开始';
            break;
        case 'NO_STARTED_0106':
            content = '活动未开启，敬请期待！\r\n请关注1月20日腾讯视频doki\r\n《明星团年饭》';
            page = '异常状态-活动未开始';
            stage = '活动未开始';
            break;
        case 'PAUSE':
            content = '活动正在升级中\r\n敬请期待';
            page = '异常状态-活动升级页';
            stage = '活动正在升级中';
            break;
        case 'ENDED':
            content = '活动已结束';
            page = '活动结束页';
            stage = '活动已结束';
            break;
        case 'NO_ACT':
            content = '此码尚未激活';
            page = '异常状态-码未激活';
            stage = '此码尚未激活';
            break;
        case 'SCRAP':
            content = '很抱歉，该码已被回收';
            page = '异常状态-二维码报废';
            stage = '该码已被回收';
            break;
        case 'limit':
            content = '您的抽奖次数已达到上限！';
            page = '当日抽奖次数达到上限';
            stage = '今天的抽奖次数已达上限';
            break;
        case 'isOther':
            content = '该二维码已被抽奖';
            page = '异常状态-二维码非本人抽奖';
            stage = '该二维码已被抽奖';
            break;
        case 'isSelf':
            content = '该二维码已被您抽过奖';
            page = '异常状态-二维码已被本人抽奖';
            stage = '该二维码已被您抽过奖';
            break;
        case 'notHit':
            content = '很遗憾，您未中奖';
            page = '异常状态-未中奖页面';
            stage = '未中奖';
            break;
        case 'outRange':
            content = '很抱歉，您不在\r\n指定的门店范围内';
            stage = '提示定位不在范围';
            break;
    }
    return { content, page, stage };
}

/**
 * 判断是否本人抽奖
 */
const checkIsSelfScan = async function (code, uri) {
    const isSelfRes = await api.request({
        url: 'tag/v2/whetherLotteryRecord',
        data: { code, uri, isSelf: true }
    })
    const { lotteryRecordVOs = {} } = isSelfRes.data;
    const { content = [] } = lotteryRecordVOs;
    let status = 'notHit';    // 未中奖
    if (content.length) {
        content.some(val => {
            if (val.poolPrizeVo) {
                status = 'isSelf';  // 本人中奖
                return true;
            }
        });
    } else {
        status = 'isOther';     // 非本人中奖
    }

    return new Promise((resolve, reject) => {
        resolve(status);
    })
}

/**
 * 扫一扫
 */
const scanCode = function () {
    wx.scanCode({
        scanType: ['qrCode'],
        onlyFromCamera: true,    // 只允许从相机扫码
        success: res => {
            const { result = '' } = res;
            if (decodeURIComponent(result).toUpperCase().includes(BOTTLEURL) || decodeURIComponent(result).toUpperCase().includes(TRACKURL)) {
                wx.reLaunch({ url: `/pages/bottle/bottle?q=${result}` });
            } else {
                wx.reLaunch({ url: `/pages/scan/scan?q=${result}&type=scan` });
            }
        }
    })
}

module.exports = {
    getUserInfo,
    updateUser,
    sendFormId,
    claimReward,
    openRedPacket,
    getWindowHeight,
    adaptiPhoneX,
    dealScanModal,
    checkIsSelfScan,
    scanCode,
}